package cz.muni.fi.pa165.bookingmanager.web;

import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

public class LoginUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
           
    public LoginUser() {
        super();
    }   	

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }  	

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            token.clear();			
                        
            response.sendRedirect("/booking_manager-web/admin/customer/all");
            return;
        } 
        catch (UnknownAccountException ex) {            
            request.setAttribute("error", ex.getMessage() );			
        } 
        catch (IncorrectCredentialsException ex) {            
            request.setAttribute("error", ex.getMessage());
        }		
        catch (Exception ex) {
            request.setAttribute("error", "Login NOT SUCCESSFUL - cause not known!");			
        }

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/backend/index.jsp");        
        dispatcher.forward(request, response);  		
    }   	  	    
}